<template>
    <div class="app-container">
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <!-- <el-button type="primary" plain size="mini" @click="handleUsb()">查看usb列表</el-button> -->
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">添加域名</el-button>
            </el-col>
            <el-col :span="3">
                <el-switch
                    v-model="autoLoginEnabled"
                    active-text="自动登录"
                    inactive-text=""
                    @change="handleAutoLoginChange">
                </el-switch>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getListFn"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="analyseList" @selection-change="handleSelectionChange">
            <!-- <el-table-column type="selection" width="55" align="center" /> -->
            <!-- <el-table-column type="expand">
                <template slot-scope="props">
                    <div class="detail-container">
                        <div class="detail-item" v-for="(file, index) in props.row.logFiles" :key="index">
                            <div class="detail-label">文件名称：</div>
                            <div class="detail-content text-name">{{ file.fileName }}</div>
                            <div class="detail-label">执行进度：</div>
                            <div class="detail-content">
                                <span v-for="(line, lineIndex) in file.fileContent.split('\n')" :key="lineIndex">
                                    {{ line }}
                                    <br v-if="lineIndex < file.fileContent.split('\n').length - 1">
                                </span>
                            </div>
                            <div class="detail-actions">
                                <el-button size="mini" type="text" @click="handleViewLog(file.filePath)">执行</el-button>
                                <el-button size="mini" type="text"
                                    @click="handleDeleteLog(file.filePath, props.row)">删除</el-button>
                            </div>
                        </div>
                        <div class="detail-item" v-if="!props.row.logFiles || props.row.logFiles.length === 0">
                            <div class="detail-content">暂无日志文件</div>
                        </div>
                    </div>
                </template>
</el-table-column> -->
            <el-table-column label="序号" prop="id" width="120" />
            <el-table-column label="域名地址" prop="usbDevice" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <span class="text-name" style="cursor: pointer" @click="handleNameClick(scope.row)">{{
                        scope.row.usbDevice }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-delete"
                        @click="handleDelete(scope.row)">删除</el-button>
                    <!-- <el-button size="mini" type="text" icon="el-icon-refresh"
                        @click="handleExec(scope.row)">执行</el-button> -->
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getListFn" />

        <!-- 添加或修改扫描配置对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
            <el-form ref="form" :model="form"  label-width="80px">
                <el-form-item label="域名地址" prop="usbDevice">
                    <el-input v-model="form.usbDevice" placeholder="请输入域名地址" />
                </el-form-item>
               
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { getNodeList } from '@/api/index'
import { addAnalyse, deleteAnalyse, getAnalyseList, getAnalyseLsUsb, getAnalyseExec, getAnalyseCatLog, getAnalyseRefresh, delAnalyseLog } from '@/api/analyse'
import autoLoginConfig from '@/config/autoLogin'

export default {
    name: "Analyse",
    data() {
        return {
            // 展开的行
            expandKeys: [],
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 分析表格数据
            analyseList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10
            },
            // 表单参数
            form: {
                param: '1',
                usbDevice: undefined
            },

            nodeList: [],
            // 自动登录开关
            autoLoginEnabled: autoLoginConfig.enabled
        };
    },
    created() {
        this.getListFn();
        this.getNodeList();
    },
    methods: {
        /** 查询分析列表 */
        getListFn() {
            this.loading = true;
            getAnalyseList(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
                this.analyseList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        /** 取消按钮 */
        cancel() {
            this.open = false;
            this.reset();
        },
        /** 表单重置 */
        reset() {
            this.form = {
                param: '1',
                usbDevice: undefined
            };
            this.resetForm("form");
        },
        /** 多选框选中数据 */
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id);
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加任务";
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const taskIds = row.id || this.ids;
            this.$modal.confirm('是否确认删除任务编号为"' + taskIds + '"的数据项？').then(function () {
                return deleteAnalyse(row.id);
            }).then(() => {
                this.getListFn();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => { });
        },
        // 获取节点列表
        getNodeList() {
            getNodeList().then(response => {
                this.nodeList = response.rows || [];
            }).catch(error => {
                this.$message.error('获取节点列表失败：' + error.message);
            });
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    addAnalyse(this.form).then(response => {
                        this.$modal.msgSuccess("新增成功");
                        this.open = false;
                        this.getListFn();
                    });
                }
            });
        },
        /** 查看日志文件 */
        handleViewLog(filePath) {
            getAnalyseCatLog({ filePath: filePath }).then(response => {
                if (response.code === 200) {
                    this.$modal.msgSuccess("查看log文件成功");
                } else {
                    this.$modal.msgError(response.msg || '查看log文件失败');
                }
            });
        },
        /** 删除日志文件 */
        handleDeleteLog(filePath, row) {
            this.$modal.confirm('是否确认删除该日志文件？').then(() => {
                return delAnalyseLog({ filePath: filePath });
            }).then(response => {
                this.$modal.msgSuccess("删除成功");
                // 只刷新当前行的日志文件列表
                getAnalyseRefresh({ id: row.id }).then(response => {
                    if (response.code === 200) {
                        this.$set(row, 'logFiles', response.data);
                    }
                });
            }).catch(() => { });
        },
        /** 执行按钮操作 */
        handleExec(row) {
            getAnalyseExec({ id: row.id }).then(response => {
                this.$modal.msgSuccess("执行成功");
            });
        },
        /** 刷新按钮操作 */
        handleRefresh() {
            getAnalyseRefresh().then(response => {
                this.$modal.msgSuccess("刷新成功");
                this.getListFn();
            });
        },
        handleNameClick(row) {
            // 检查域名格式并添加http前缀（如果需要）
            let url = row.usbDevice;
            if (!url.startsWith('http://') && !url.startsWith('https://')) {
                url = 'http://' + url;
            }
            // 在新标签页中打开域名
            window.open(url, '_blank');
        },
        handleUsb() {
            getAnalyseLsUsb().then(response => {
                if (response.code === 200 && response.data) {
                    this.$modal.alert(
                        response.data.content.split('\n').map(line => line.trim()).join('\n'),
                        "USB设备列表",
                        {
                            dangerouslyUseHTMLString: true,
                            confirmButtonText: '确定',
                            callback: action => { }
                        }
                    );
                } else {
                    this.$modal.msgError(response.msg || 'USB列表获取失败');
                }
            });
        },
        /** 处理自动登录开关变化 */
        handleAutoLoginChange(value) {
            // 更新配置
            autoLoginConfig.enabled = value;
            // 保存到localStorage
            localStorage.setItem('autoLoginEnabled', JSON.stringify(value));
            this.$modal.msgSuccess(value ? "已启用自动登录" : "已禁用自动登录");
        }
    }
};
</script>

<style lang="scss" scoped>
.detail-container {
    padding: 20px;
    background: #f8f8f8;
    border-radius: 4px;
    margin: 10px 20px;

    .detail-item {
        margin-bottom: 15px;

        &:last-child {
            margin-bottom: 0;
        }

        .detail-label {
            font-weight: bold;
            color: #606266;
            margin-bottom: 5px;
        }

        .detail-content {
            color: #333;
            line-height: 1.5;
            word-break: break-all;
            white-space: pre-wrap;
        }

        .detail-actions {
            margin-top: 8px;

            .el-button {
                padding: 4px 8px;
                margin-right: 8px;

                &:last-child {
                    margin-right: 0;
                }
            }
        }
    }
}

.text-name {
    color: #409EFF !important;
}
</style>
